<?php
class model_KarmaMapper {
    private $table = 'karma';
    private $userTable = 'users';

    public function  __construct() {
        model_ConfigMapper::connect();
    }

    public function find($post) {
        $query = 'SELECT karma from '. $this->userTable .' WHERE id = '. $post['id'];
        $result = mysql_query($query);
        $row = mysql_fetch_assoc($result);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        return $row['karma'];
    }

    public function validVote($t, $post) {
        $user = model_UserMapper::getCurrentUser();
        $query = 'SELECT date from '. $this->table .' WHERE kto = '. $user->getId() .' and zakogo='. $post['id'] .' ORDER BY date DESC';
        $result = mysql_query($query);
        $row = mysql_fetch_assoc($result);

        $prevTime = $row['date'];

        $currTime = time();

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        if($currTime - $prevTime > $t) {
            return true;
        } else {
            return false;
        }
    }

    public function vote($post) { //находим сообщение, записываем его содержание в свойства объекта
        $user = model_UserMapper::getCurrentUser();
        $query = 'INSERT INTO '. $this->table .' (kto, zakogo, golos, date) VALUES ("'. $user->getId() .'","'. $post['id'] .'","'. $post['vote'] .'","'. time() .'")';
        $result = mysql_query($query);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();
    }

    public function upKarma($post) {
        $query = 'UPDATE '. $this->userTable .' SET karma=karma+10 WHERE id='. $post['id'];
        $result = mysql_query($query);
    }

    public function downKarma($post) {
        $query = 'UPDATE '.$this->userTable .' SET karma=karma-10 WHERE id='. $post['id'];
        $result = mysql_query($query);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();
    }

    public function update($post) {
        $query = 'SELECT karma from '. $this->userTable .' WHERE id = '. $post['id'];
        $result = mysql_query($query);
        $row = mysql_fetch_assoc($result);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        return $row['karma'];
    }
}